package com.aigao.golf.common.shiro

import org.apache.shiro.util.StringUtils
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager

import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletResponse
import java.io.Serializable

class ShiroWebSessionManager : DefaultWebSessionManager() {
    var accessControlAllowMethods = "GET, POST, PUT, OPTIONS, DELETE"
    var accessControlAllowHeaders = "x-requested-with, content-type"
    var accessControlMaxAge = "3600"
    var accessControlAllowOrigin: String? = null

    override fun getSessionId(request: ServletRequest, response: ServletResponse): Serializable? {
        if (response is HttpServletResponse && StringUtils.hasText(this.accessControlAllowOrigin)) {
            response.setHeader("Access-Control-Allow-Origin", this.accessControlAllowOrigin)
            response.setHeader("Access-Control-Allow-Methods", this.accessControlAllowMethods)
            response.setHeader("Access-Control-Max-Age", this.accessControlMaxAge)
            response.setHeader("Access-Control-Allow-Headers", this.accessControlAllowHeaders)
            response.setHeader("Access-Control-Allow-Credentials", "true")
        }

        return super.getSessionId(request, response)
    }

    companion object {
        private val DEF_ACCESS_CONTROL_ALLOW_METHODS = "GET, POST, PUT, OPTIONS, DELETE"
        private val DEF_ACCESS_CONTROL_ALLOW_HEADERS = "x-requested-with, content-type"
        private val DEF_ACCESS_CONTROL_MAX_AGE = "3600"
    }
}
